package com.dlz.systemshop.controller;

import com.dlz.systemshop.pojo.APIResponse;
import com.dlz.systemshop.service.UserService;
import com.dlz.systemshop.utils.ServerAddressUtil;
import com.dlz.systemshop.utils.UpLoadUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;

/**
 * @author 你的姓名
 * @date 2025/1/3 13:47
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/uploadAvatar")
    public String uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if(file==null){
            throw new RuntimeException("上传文件为空");
        }
        return ServerAddressUtil.getURLExURI(request)+UpLoadUtil.uploadImage(file,"upload/image/user");
    }

    @RequestMapping("/saveAvatarURL")
    public Boolean saveAvatarPath(@RequestBody Map<String,String> params,HttpServletRequest request){
        String username = params.get("username");
        String url = params.get("url");
        // 获取服务器地址
        String serverAddress = ServerAddressUtil.getURLExURI(request);

        // 提取相对路径
        String relativePath = url.replace(serverAddress, "");

        // 确保相对路径不以斜杠开头
        if (relativePath.startsWith("/")) {
            relativePath = relativePath.substring(1);
        }
        return userService.saveVatar(username,relativePath);
    }

    @RequestMapping("/getAvatarURL")
    @ResponseBody
    public APIResponse<String> getAvatarURL(String userName){
        String avatarURL = userService.getAvatarURL(userName);
        return APIResponse.success(avatarURL);
    }
}
